/**
 * Copyright (C) 2013-2014 the original author or authors.
 */
package com.foreveross.bsl;

import java.io.PrintStream;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * xxx
 *
 * @author Wangyi
 * @version v1.0
 *
 * @date 2013-12-6
 *
 */
public class MessageStatistics {
	
	private AtomicInteger receivedCount;
	private AtomicInteger receiptCount, receiptErrorCount;
	private long minArrivedDelay, maxArrivedDelay;
	
	/**
	 * 
	 */
	public MessageStatistics() {
		this.receivedCount=new AtomicInteger();
		this.receiptCount=new AtomicInteger();
		this.receiptErrorCount=new AtomicInteger();
		this.maxArrivedDelay=0;
		this.minArrivedDelay=0;
	}
	
	public void reset(){
		this.receivedCount.set(0);
		this.receiptCount.set(0);
		this.maxArrivedDelay=0;
		this.minArrivedDelay=0;
	}
	
	public int count(PushMessage msg){
		long delay=msg.getArrivedDelay();
		synchronized (this) {
			if(this.maxArrivedDelay==0 || this.maxArrivedDelay<delay){
				this.maxArrivedDelay=delay;
			}
			if(this.minArrivedDelay==0 || this.minArrivedDelay>delay){
				this.minArrivedDelay=delay;
			}
		}
		return receivedCount.incrementAndGet();
	}
	
	public int countReceipt(boolean okReceipt){
		if(okReceipt){
			return this.receiptCount.incrementAndGet();
		}
		else{
			return this.receiptErrorCount.incrementAndGet();
		}
	}
	
	public void print(PrintStream ps){
		ps.println("--------------------------");
		ps.println("接收计数："+this.receivedCount);
		ps.println("回执计数："+this.receivedCount+"(错误："+this.receiptErrorCount+")");
		ps.println("从发出到接收最小用时："+this.minArrivedDelay+"ms");
		ps.println("从发出到接收最大用时："+this.maxArrivedDelay+"ms");
		ps.println("--------------------------");
	}
	
	public void print(){
		this.print(System.out);
	}

	/**
	 * @return the receivedCount
	 */
	public int getReceivedCount() {
		return receivedCount.get();
	}

	/**
	 * @return the minArrivedDelay
	 */
	public synchronized long getMinArrivedDelay() {
		return minArrivedDelay;
	}

	/**
	 * @return the maxArrivedDelay
	 */
	public synchronized long getMaxArrivedDelay() {
		return maxArrivedDelay;
	}

	/**
	 * @return the receiptCount
	 */
	public int getReceiptCount() {
		return receiptCount.get();
	}
	
	public int getReceiptErrorCount() {
		return receiptErrorCount.get();
	}

}
